<template>
    <div id="header" style="display:flex; flex-direction: row; width: 100%;">
        <div style="width: 40%;">
            <div id="logo"><img src="../assets/logo.jpg" alt=""></div>
        </div>

        <div style="width: 60%; display: flex;flex-direction: row; justify-content: flex-end; margin-right: 5%;">
            <div class="headerinfo"><a href="#">帮助中心</a></div>
            <div class="headerinfo"><a href="#">购物车</a></div>
            <div class="headerinfo"><a href="#">收藏夹</a></div>
            <div class="headerinfo"><a href="#">个人资料</a></div>
            <div class="headerinfo"><a href="#">退出登录</a></div>
            <div>
                <el-avatar style="height: 100%; width: 100%;"
                    src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png">
                </el-avatar>
            </div>
        </div>
    </div>


    <div class="container">
        <!-- 顶部轮播图 -->
        <section class="carousel-section">
            <el-carousel height="300px" interval="3000" arrow="hover">
                <el-carousel-item v-for="(item, index) in carouselImages" :key="index">
                    <img :src="item" class="carousel-image" />
                </el-carousel-item>
            </el-carousel>
        </section>

        <!-- 排序与筛选 -->
        <section class="filter-bar">
            <button class="filter-button" @click="sortByPrice">按价格排序 {{ isASC ? '↑' : '↓' }}</button>
            <button class="filter-button" @click="sortByCategory">按分类排序</button>
        </section>

        <!-- 主内容区域 -->
        <main class="main-content">
            <h2 class="section-title">商品推荐</h2>
            <section class="goods-grid">
                <el-card v-for="item in goodsList" :key="item.productId" class="goods-card">
                    <img :src="item.imageurl" class="goods-image" alt="商品图片" />
                    <div class="goods-name">{{ item.gname }}</div>
                    <div class="goods-brand">品牌：{{ item.gbrand }}</div>
                    <div class="goods-category">分类：{{ item.gcatagory }}</div>
                    <div class="goods-price">￥{{ item.gsellprice }}</div>
                    <div class="goods-stock">库存：{{ item.gstock }}</div>
                </el-card>
            </section>

            <!-- 分页组件 -->
            <div class="pagination-wrapper">
                <el-pagination background layout="prev, pager, next" :total="total" :page-size="size" :current-page="page"
                    @current-change="handlePageChange" />
            </div>
        </main>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from "@/api/api";
import { ElLoading, ElMessage } from 'element-plus'//引入element-plus的JS服务

const page = ref(1)
const size = 6
const total = ref(0)
const goodsList = ref([])
const isASC = ref(1)
const loading = ref(false)
const sortByCategoryValue = ref(false)

console.log('ElMessage:', ElMessage)

const carouselImages = [
    'https://www.bing.com/th/id/OIP.n7A91iiJxVZkHULqVxAIPAHaD2?w=332&h=180&c=7&r=0&o=5&dpr=1.1&pid=1.7',
    'https://www.bing.com/th/id/OIP.JWd41WnuhA3P27OYRb4o5AHaF7?w=221&h=180&c=7&r=0&o=5&dpr=1.1&pid=1.7',
    'https://www.bing.com/th/id/OIP.D6zLl5PBLypcN9VGXjw85wHaDd?w=308&h=163&c=7&r=0&o=5&dpr=1.1&pid=1.7'
]

const fetchGoods = async () => {
    loading.value = true

    const loadingInstance = ElLoading.service({
        lock: true,                  // 锁住页面
        text: '加载中，请稍候...',     // 显示的文字
        background: 'rgba(0, 0, 0, 0.3)',  // 背景半透明
    })
    const startTime = Date.now()//创建加载时间对象

    const duration = Date.now() - startTime

    const minDisplayTime = 1000  // 最少展示 500ms
    //优化加载显示，使加载时间至少500ms，多了再加
    if (duration < minDisplayTime) {
        await new Promise(resolve => setTimeout(resolve, minDisplayTime - duration))
    }

    try {
        const res = await api.get(`goods/F_G_By_Price`, {
            params: {
                isASC: isASC.value,
                page: page.value,
                size
            }
        })

        const TotalCountres = await api.get(`goods/CountGoods`)
        goodsList.value = res.data
        total.value = TotalCountres.data
    } catch (err) {
        // console.error('获取商品数据失败', err)
        ElMessage.error('获取商品数据失败', err)
    } finally {
        loading.value = false
        loadingInstance.close()
    }
}

const handlePageChange = (val) => {
    page.value = val
    fetchGoods()
}

const sortByPrice = () => {
    isASC.value = isASC.value === 1 ? 0 : 1
    page.value = 1
    fetchGoods()
}

const sortByCategory = () => {
    sortByCategoryValue.value = !sortByCategoryValue.value
    // console.log('实现按分类请求的逻辑')
    //fetchByCategory(sortByCategoryValue.value)
}

onMounted(() => {
    fetchGoods()
})
</script>

<style>
.container {
    width: 100%;
    min-height: 100vh;
    background-color: #f9fafb;
}

.carousel-section {
    width: 100%;
    margin-bottom: 40px;
}

.carousel-image {
    width: 100%;
    height: 300px;
    object-fit: cover;
    border-radius: 8px;
}

.filter-bar {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-bottom: 24px;
}

.filter-button {
    padding: 8px 16px;
    border: 1px solid #ccc;
    background-color: white;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.filter-button:hover {
    background-color: #f3f4f6;
}

.main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 24px;
}

.section-title {
    font-size: 24px;
    font-weight: bold;
    color: #374151;
    margin-bottom: 24px;
}

.goods-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
}

.goods-card {
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: box-shadow 0.3s;
    background-color: #fff;
    padding: 16px;
}

.goods-card:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.goods-image {
    width: 100%;
    height: 192px;
    object-fit: contain;
    border-radius: 8px;
    margin-bottom: 8px;
}

.goods-name {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.goods-brand,
.goods-category,
.goods-stock {
    font-size: 14px;
    color: #6b7280;
}

.goods-price {
    color: #ef4444;
    font-weight: bold;
    margin-top: 8px;
    font-size: 16px;
}

.pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 48px;
}

.loading {
    text-align: center;
    font-size: 16px;
    color: #999;
    margin-top: 24px;
}
</style>
